package cn.sdc.sfw.dao.handler.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;

import javax.sql.DataSource;

import cn.sdc.sfw.dao.exception.DaoException;
import cn.sdc.sfw.dao.handler.BasicHandler;
import cn.sdc.sfw.dao.handler.DbHandler;
import cn.sdc.sfw.dao.handler.UpdateHandler;

/**
 * @author sdc
 *
 */
public class UpdateHandlerImpl extends BasicHandler implements UpdateHandler {
	
	public UpdateHandlerImpl() {
	}

	public UpdateHandlerImpl(DataSource dataSource, String sql) {
		super(dataSource, sql);
	}

	public int execute() throws DaoException {
		return execute(null, null);
	}
	
	public int execute(Object[] args) throws DaoException {
		return execute(args, getArgTypes(args));
	}
	
	public int execute(Object[] args, Class[] argTypes) throws DaoException {
		Connection connection = getConnection();
		int resultLine = 0;
		try {
			System.out.println("[START SQL]~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
			System.out.println(getCompleteSql(args));
			System.out.println("[END   SQL]~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
			resultLine = execute(connection, args, argTypes);
		} finally {
//			DbHandler.commitConnection(connection);
//			DbHandler.closeConnection(connection);
		}
		return resultLine;
	}

	protected int execute(Connection connection, Object[] args, Class[] argTypes) {
		PreparedStatement ps = prepareStatement(connection);
		int resultLine = 0;
		try {
			if(args != null && args.length > 0){
				bindArgs(ps, args, argTypes);
			}
			resultLine = DbHandler.executeUpdate(ps);
		} finally {
			DbHandler.closeStatement(ps);
		}
		return resultLine;
	}
}